package
{
	import com.wp.datacontainer.map.HashMap;
	
	import data.AreaLineAvatar;
	import data.EffectAvatar;
	import data.MapLayerData;
	import data.MonsterAvatar;
	import data.NpcAvatar;
	import data.TransPointAvatar;
	import data.WalkData;
	import data.db.MapDB;
	import data.db.MonsterDB;
	import data.db.NpcDB;
	import data.type.MapLayerType;
	
	import editors.AreaLine;
	
	import engine.animation.AnimationClip;
	import engine.manager.AnimationFactory;
	
	import events.MapEvent;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import mx.collections.Sort;
	import mx.collections.SortField;
	
	import utils.EventManager;

	/**
	 * 资源工具
	 * wuxi create on 2012-10-10 22:31:18
	 * */
	public class MapResourceUtil
	{
		public function MapResourceUtil()
		{
		}
		
		private static var _configLoader : URLLoader;
		private static var _urlRequest : URLRequest;
		private static var _imageLoader : Loader;
		
		/**
		 * 加载地图资源文件
		 * @param url资源地址
		 * */
		public static function loadMapConfig(url:String):void{
			if(!_configLoader){
				_configLoader = new URLLoader();
				_urlRequest = new URLRequest();
				
				//_configLoader.addEventListener(ProgressEvent.PROGRESS, onProgressHandler);
				_configLoader.addEventListener(Event.COMPLETE, onConfigLoadComplate);
				_configLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
				_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError);
			}
			_urlRequest.url = url + ".xml";//"\\"+MapData.editMap.xml_uri+".xml";
			_configLoader.load(_urlRequest);
			
			if(!_imageLoader){
				_imageLoader = new Loader();
				_imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImage, false, 0, true);
				_imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError, false, 100, true);
				_imageLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError, false, 0, true);
			}
			/*_urlRequest.url = "";
			_imageLoader.load(_urlRequest);*/
		}
		
		private static function onConfigLoadComplate(event : Event):void{
			_configLoader.close();
			var configXML : XML = XML(event.target.data);
			// 解析所有数据
			MapData.mapWidth = configXML.mapInfo.@w;
			MapData.mapHeight = configXML.mapInfo.@h;
			MapData.mapGridSize = configXML.mapInfo.@s;
			
			MapData.walkWidth = configXML.walkArea.@w;
			MapData.walkHeight = configXML.walkArea.@h;
			MapData.walkX = configXML.walkArea.@x;
			MapData.walkY = configXML.walkArea.@y;
			MapData.bornX = configXML.walkArea.@bx;
			MapData.bornY = configXML.walkArea.@by;
			
			
			MapData.mapLayers.removeAll();
			MapData.grounds.removeAll();
			MapData.npcs.removeAll();
			MapData.monsters.removeAll();
			MapData.areas.removeAll();
			
			// 解析地图图层信息
			
			var forLayers : XMLList = configXML.forLayers.layer;
			var backLayers : XMLList = configXML.backLayers.layer;
			var layerData : MapLayerData;
			var iamgeArr:Array;
			for each (var layerXML:XML in forLayers) {
				layerData = new MapLayerData();
				layerData.layerX = layerXML.@x;
				layerData.layerY = layerXML.@y;
				layerData.imagePath = layerXML.@p;
				layerData.layerDepth = layerXML.@d;
				layerData.layer = layerXML.@l;
				iamgeArr = layerData.imagePath.split(".");
				layerData.imageName = iamgeArr[0];
				layerData.imageType = iamgeArr[1];
				layerData.width = layerXML.@w;
				layerData.height = layerXML.@h;
				MapData.mapLayers.addItem(layerData);
			}
			for each (layerXML in backLayers) {
				layerData = new MapLayerData();
				layerData.layerX = layerXML.@x;
				layerData.layerY = layerXML.@y;
				layerData.imagePath = layerXML.@p;
				layerData.layerDepth = layerXML.@d;
				layerData.layer = layerXML.@l;
				iamgeArr = layerData.imagePath.split(".");
				layerData.imageName = iamgeArr[0];
				layerData.imageType = iamgeArr[1];
				layerData.width = layerXML.@w;
				layerData.height = layerXML.@h;
				MapData.mapLayers.addItem(layerData);
			}
			var sort:Sort = new Sort();
			var sortfieldLastName:SortField = new SortField("layerDepth",true);
			var sortfieldLastName1:SortField = new SortField("layer",true);
			sort.fields = [sortfieldLastName1,sortfieldLastName];
			MapData.mapLayers.sort = sort;
			MapData.mapLayers.refresh();
			
			
			
			/* 添加前后景的效果 */
			var foreEffectXMLList:XMLList = configXML.forEffects.effect;
			var backEffectXMLList:XMLList = configXML.backEffects.effect;
			MapData.effects.removeAll();
			var effectAvatar:EffectAvatar;
			for each(var effectXML:XML in foreEffectXMLList){
				effectAvatar = new EffectAvatar();
				effectAvatar.name = effectXML.@p;
				
				var effectAC:AnimationClip = new engine.animation.AnimationClip();
				effectAC.state = "idle";
				effectAC.registerAnimationFactory(AnimationFactory.getByTextureAsset("http://deploystatic.blessjoy.com/chronicleweb/asset/mapeffect/" + effectAvatar.name,1));
				
				effectAvatar.avatar = effectAC;
				
				effectAC.x = effectAvatar.gridX = effectXML.@x;
				effectAC.y = effectAvatar.gridY = effectXML.@y;
				effectAvatar.layer = MapLayerType.LAYER_FORE;
				MapData.effects.addItem(effectAvatar);
			}
			for each(effectXML in backEffectXMLList){
				effectAvatar = new EffectAvatar();
				effectAvatar.name = effectXML.@p;
				var effectAC:AnimationClip = new AnimationClip();
				effectAC.state = "idle";
				effectAC.registerAnimationFactory(AnimationFactory.getByTextureAsset("http://deploystatic.blessjoy.com/chronicleweb/asset/mapeffect/" + effectAvatar.name,1));
				effectAvatar.avatar = effectAC;
				effectAC.x = effectAvatar.gridX = effectXML.@x;
				effectAC.y = effectAvatar.gridY = effectXML.@y;
				effectAvatar.layer = MapLayerType.LAYER_BACK;
				MapData.effects.addItem(effectAvatar);
			}
			
			// 解析行走区域  遮挡点以及半透区域
			MapData.walkArr = new HashMap();
			var tiles : XMLList = configXML.tiles.tl;
			var walkData : WalkData;
			for each (var tileXML:XML in tiles) {
				walkData = new WalkData();
				walkData.gridX = int(tileXML.@x) + 1;
				walkData.gridY = int(tileXML.@y) + 1;
				walkData.type = tileXML.@t;
				MapData.walkArr.put(walkData.gridX+"_"+walkData.gridY,walkData);
			}
			
			// 解析地图中的区域信息
			var areaList:XMLList = configXML.walkArea.area;
			var areaLineAvatar:AreaLineAvatar;
			for each(var areaXML:XML in areaList){
				areaLineAvatar = new AreaLineAvatar();
				areaLineAvatar.avatarID = areaXML.@id;
				areaLineAvatar.x = areaXML.@x;
				areaLineAvatar.width = areaXML.@w;
				areaLineAvatar.avatar = new AreaLine();
				AreaLine(areaLineAvatar.avatar).areaTitle = "区域"+areaLineAvatar.avatarID;
				MapData.areas.addItem(areaLineAvatar);
			}
			// 解析传送点
			var trans : XMLList = configXML.grounds.tp;
			var transData : TransPointAvatar;
			for each (var tranXML:XML in trans) {
				transData = new TransPointAvatar();
				transData.gridX = int(tranXML.@x) + 1;
				transData.gridY = int(tranXML.@y) + 1;
				transData.avatarID = tranXML.@id;
				transData.targetMapID = tranXML.@mapid;
				if(MapData.db_maps.getValue(transData.targetMapID)){
					transData.targetMapName = MapDB(MapData.db_maps.getValue(transData.targetMapID)).name;
					transData.targetMapName = transData.targetMapName == "" ? "未找到地图" : transData.targetMapName;
				}
				transData.avatar = new Trans();
				MapData.grounds.addItem(transData);
			}
			// 解析npc
			var npcs : XMLList = configXML.npcs.n;
			var npcData : NpcAvatar;
			for each (var npcXML:XML in npcs) {
				npcData = new NpcAvatar();
				npcData.gridX = int(npcXML.@x) + 1;
				npcData.gridY = int(npcXML.@y) + 1;
				npcData.avatarID = npcXML.@id;
				var npcDB:NpcDB = NpcDB(MapData.db_npcs.getValue(npcData.avatarID));
				if(npcDB){
					npcData.resourID = npcDB.body_id;
					npcData.npcName = npcDB.name;
				}
				else{
					npcData.npcName = "是不是把我删除了?";
				}
				
				npcData.avatar = new Npc();
				MapData.npcs.addItem(npcData);
			}
			MapData.npcs.refresh();
			// 解析怪物
			var monsters : XMLList = configXML.monsters.m;
			var monsterData : MonsterAvatar;
			for each (var monsterXML:XML in monsters) {
				monsterData = new MonsterAvatar();
				monsterData.gridX = int(monsterXML.@x) + 1;
				monsterData.gridY = int(monsterXML.@y) + 1;
				monsterData.avatarID = monsterXML.@id;
				var monsterDB:MonsterDB = MonsterDB(MapData.db_monsters.getValue(monsterData.avatarID));
				if(monsterDB){
					monsterData.resourceID = monsterDB.body_id;
					monsterData.monsterName = monsterDB.name;
					monsterData.monsterType = monsterDB.type;
				}
				else{
					monsterData.monsterName = "哎?是不是把我删了？";
				}
				var monsterMC:MovieClip = new Monster();
				monsterData.avatar = monsterMC;
				trace(monsterData.avatarID + ' III +' + monsterMC.nameText +'+ sfasf ' + monsterData.monsterName);
				monsterMC.nameText.text = monsterData.avatarID + '  ' + monsterData.monsterName;
				MapData.monsters.addItem(monsterData);
				trace(monsterMC.nameText.visible);
			}
			MapData.monsters.refresh();
			
			EventManager.getInstance().dispatchEvent(new MapEvent(MapEvent.EDIT_MAPRESOURCE));
		}
		                  
		private static function onLoadedImage(event:Event):void{
			
		}
		
		private static function onLoadError(error:ErrorEvent):void{
			trace("加载失败,重置地图资源数据！");
			MapData.clear();
			EventManager.getInstance().dispatchEvent(new MapEvent(MapEvent.EDIT_MAPRESOURCE));
		}
		/**
		 * 将当前编辑的地图数据导出成xml
		 * */
	    public static function exportXML():XML{
			var xml:XML = <root/>;
			
			var mapInfoXML:XML = <mapInfo s={MapData.mapGridSize} w={MapData.mapWidth} h={MapData.mapHeight}/>;
			var mapWalkAreaXML:XML = <walkArea x={MapData.walkX} y={MapData.walkY} w={MapData.walkWidth} h={MapData.walkHeight} bx={(MapData.bornX - 1 < 0 ? 0 : MapData.bornX - 1)} by={MapData.bornY - 1 < 0 ? 0 : MapData.bornY - 1}/>;
			                          
			for each(var areaData:AreaLineAvatar in MapData.areas){
				var areaXML:XML = <area w={areaData.width} x={areaData.x} id={areaData.avatarID}/>;
				mapWalkAreaXML.appendChild(areaXML);
			}
			
			/* 添加地图图层 */ 
			var forLayerXML:XML = <forLayers/>;
			var backLayerXML:XML = <backLayers/>;
			var layers:Array = (MapData.mapLayers.toArray());
			layers.sort();
			for each(var layerData:MapLayerData in layers){
				var layer:XML = <layer l={layerData.layer} d={layerData.layerDepth} p={layerData.imagePath} x={layerData.layerX} y={layerData.layerY} w={layerData.imageData.width} h={layerData.imageData.height}/>
				if(layerData.layer == MapLayerType.LAYER_FORE){ // 前
					forLayerXML.appendChild(layer);
				}
				else if(layerData.layer == MapLayerType.LAYER_BACK){ // 后
					backLayerXML.appendChild(layer);
				}
			}
			/* 添加前后景的效果 */
			var foreEffectXML:XML = <forEffects/>;
			var backEffectXML:XML = <backEffects/>;
			var effects:Array = MapData.effects.toArray();
			effects.sort();
			for each(var effectAvatar:EffectAvatar in effects){
				var effect:XML = <effect p={effectAvatar.name} x={effectAvatar.gridX} y={effectAvatar.gridY}/>;
				if(effectAvatar.layer == MapLayerType.LAYER_FORE){
					foreEffectXML.appendChild(effect);
				}
				else if(effectAvatar.layer == MapLayerType.LAYER_BACK){
					backEffectXML.appendChild(effect);
				}
			}
			
			/* 添加地图遮挡点信息 */
			var tileXML:XML = <tiles/>;
			var tiles:Array = MapData.walkArr.values();
			for each(var walkData:WalkData in tiles){
				var tile:XML = <tl t={walkData.type} x={walkData.gridX - 1} y={walkData.gridY -1 }/>;
				tileXML.appendChild(tile);
			}
			
			/* 添加地物层 主要是 传送点 */
			var groundXML:XML = <grounds/>
			var grounds:Array = MapData.grounds.toArray();
			grounds.sort();
			for each(var transData:TransPointAvatar in grounds){
				var trans:XML = <tp id={transData.avatarID} x={transData.gridX - 1} y={transData.gridY - 1} mapid={transData.targetMapID}
				                     aId={getAreaIDByPos((transData.gridX + 0.5) * MapData.mapGridSize)}/>
				groundXML.appendChild(trans);
			}
			
			/* 添加地图Npc区域 */
			var npcXML:XML = <npcs/>;
			var npcs:Array = MapData.npcs.toArray();
			npcs.sort();
			for each(var npcAvatar:NpcAvatar in npcs){
				var npc:XML = <n id={npcAvatar.avatarID} x={npcAvatar.gridX - 1} y={npcAvatar.gridY - 1}
								  aId={getAreaIDByPos((npcAvatar.gridX + 0.5) * MapData.mapGridSize)}/>;
				npcXML.appendChild(npc);
			}
			/* 添加地图怪物 */
			var monsterXML:XML = <monsters/>;
			var monsters:Array = MapData.monsters.toArray();
			monsters.sortOn("gridX",Array.NUMERIC);
			for each(var monsterAvatar:MonsterAvatar in monsters){
				var monster:XML = <m id={monsterAvatar.avatarID} x={monsterAvatar.gridX - 1} y={monsterAvatar.gridY - 1}
								  aId={getAreaIDByPos((monsterAvatar.gridX + 0.5) * MapData.mapGridSize)}/>;
				monsterXML.appendChild(monster);
			}
			
			
			xml.appendChild(mapInfoXML);
			xml.appendChild(mapWalkAreaXML);
			xml.appendChild(forLayerXML);
			xml.appendChild(backLayerXML);
			
			xml.appendChild(foreEffectXML);
			xml.appendChild(backEffectXML);
			
			xml.appendChild(tileXML);
			xml.appendChild(groundXML);
			xml.appendChild(npcXML);
			xml.appendChild(monsterXML);
			
			return xml;
		}
		
		/**
		 * 根据当前位置来决定 npc、怪物、传送点属于哪个区域
		 * @return -1标示属于整个地图范围，一般应用于 城镇。 副本一般都是按照区域来加载和显示的
		 * */
		private static function getAreaIDByPos(posX:int):int{
			if(!MapData.areas || MapData.areas.length == 0){
				return -1;
			}
			for each(var areaLineAvatar:AreaLineAvatar in MapData.areas){
				if(posX >= areaLineAvatar.x && posX <= areaLineAvatar.x + areaLineAvatar.width){
					return areaLineAvatar.avatarID;
				}
			}
			
			return 0;
		}
	}
}